<template>
  <el-tooltip class="item" effect="dark" :content="fileName" placement="top">
    <zm-button :loading="loading" type="text" @click="toDownload" class="toe">
      {{fileName}}
    </zm-button>
  </el-tooltip>
</template>
<script>
import axios from 'axios'

export default {
  name: 'ZmEnclosure',
  props: {
    fileUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {
    fileName () {
      let temp = []
      let fileUrl = this.fileUrl || ''
      temp = fileUrl.split('/')
      let name = (temp.length && temp[temp.length - 1]) || '文件名不对'
      return name
    }
  },
  created () { },
  mounted () { },
  methods: {
    getBlobExport (params, url) {
      return axios({
        url: `${url}`,
        params,
        responseType: 'blob'
      })
    },
    async toDownload () {
      this.loading = true
      try {
        let res = await this.getBlobExport(
          { fileUrl: this.fileUrl },
          'upload/downLoad'
        )
        this.loading = false
        this.downloadFile(res)
      } catch (error) {
        this.loading = false
      }
    },
    downloadFile (blob) {
      if (!blob || !blob.data) {
        return
      }
      let _blob = new Blob([blob.data])
      let url = window.URL.createObjectURL(_blob)
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', this.fileName || '下载.png')
      document.body.appendChild(link)
      link.click()
      setTimeout(() => {
        document.body.removeChild(link)
      }, 20000)
    }
  }
}
</script>
